#include "attendwim.h"
#include "ui_attendwim.h"

#include <QDateTime>
#include <QThread>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>


AttendWim::AttendWim(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::AttendWim)
{
    ui->setupUi(this);
    // 监听，启动服务器 当有客户端连接发送信号newconnection
    connect(&mserver,&QTcpServer::newConnection,this,&AttendWim::accept_client);
    mserver.listen(QHostAddress::Any,9999);
    bsize = 0;

    // 给sql模型绑定表格
    model.setTable("employee");

    QThread *thread = new QThread();
    // 把qfaceobj对象
    fobj.moveToThread(thread);
    thread->start();            // 启动线程
    connect(this,&AttendWim::query,&fobj,&QFaceObject::face_query);// 信号槽触发线程

    // 关联QFaceObject对象中的
    connect(&fobj,&QFaceObject::send_faceid,this,&AttendWim::recv_faceid);

}

AttendWim::~AttendWim()
{
    delete ui;
}
void AttendWim::accept_client()
{
    // 获取客户端通信的套接字
    msocket = mserver.nextPendingConnection();
    // 当客户端有数据到达
    connect(msocket,&QTcpSocket::readyRead,this,&AttendWim::read_data);
}
void AttendWim::read_data(){
    QDataStream stream(msocket);    //套接字绑定到流上
    stream.setVersion(QDataStream::Qt_5_12);

    if(bsize == 0)
    {
        if(msocket->bytesAvailable() < (qint64)sizeof (bsize))
            return;
        // 采集数据的长度
        stream >> bsize;
    }
    if(msocket->bytesAvailable() < bsize)
    {
        //说明数据还没有发送完成，返回继续等待
        return;
    }

    QByteArray data;
    stream >> data;
    bsize = 0;
    if(data.size() == 0)    //没有读到数据
    {
        return;
    }

    // 显示图片
    QPixmap mmp;
    mmp.loadFromData(data,"jpg");
    mmp = mmp.scaled(ui->picLb->size());
    ui->picLb->setPixmap(mmp);


    // 客户端传来的识别人脸信息
    cv::Mat faceImage;
    std::vector<uchar> decode;
    decode.resize(data.size());
    memcpy(decode.data(),data.data(),data.size());

    faceImage = cv::imdecode(decode,cv::IMREAD_COLOR);
    emit query(faceImage);
    //int faceid = fobj.face_query(faceImage);
   // qDebug()<<faceid;



}
// 从数据库查询faceid个人信息
void AttendWim::recv_faceid(int64_t faceid)
{
    qDebug()<<"识别到的人脸ID为"<<faceid;
    if(faceid < 0)
    {
        QString sdmsg = QString("{\"employeeID\":\"\",\"name\":\"\",\"department\":\"\",\"time\":\"\"}");
        msocket->write(sdmsg.toUtf8());
        return;
    }
    // 给模型设置过滤器
    model.setFilter(QString("faceID=%1").arg(faceid));  // 根据ID过滤查询到的人是谁
    // 查询
    model.select();
    // 判断是否查询到数据
    if(model.rowCount() == 1)
    {
        // 工号，姓名，部门，时间
        // {"employeeID":%1,"name":%2,department:冉健,time:%3}
        QSqlRecord record = model.record(0);
        QString sdmsg = QString("{\"employeeID\":\"%1\",\"name\":\"%2\",\"department\":\"冉健\",\"time\":\"%3\"}"
                                ).arg(record.value("employeeID").toString()
                                      ).arg(record.value("name").toString()
                                            ).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

        // 数据写入考勤表
        QString insertSql = QString("insert into attendance(employeeID) values('%1')").arg(record.value("employeeID").toString());
        QSqlQuery query;
        if(query.exec(insertSql))
        {
            QString sdmsg = QString("{\"employeeID\":\"\",\"name\":\"\",\"department\":\"\",\"time\":\"\"}");
            msocket->write(sdmsg.toUtf8());
            qDebug()<<query.lastError().text();
            return ;
        }
        else
        {
            msocket->write(sdmsg.toUtf8()); // 把查询到的数据发送给客户端
        }

    }
}
